<script type="text/ecmascript-6">
  /**
   * Created by wcz on 2017/1/7.
   * import b from '../bus'
   */
  export default {
    data () {
      return {
        comments: [],
        pageIndex: 1,
        pageSize: 15,
        total: 0,
        imgVisible: false,
        pointImgSlim: '',
        pointMsg: '',
        searchForm: {
          state: '3',
          name: '',
          car_num: '',
          city: '',
          down_role: ''
        },
        activityStatus: false,
        geocoder: null,
        cdn: window.cdn
      }
    },
    created () {
      AMap.service('AMap.Geocoder', () => {
        //实例化Geocoder
        this.geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
      })
    },
    computed: {
      isListEmpty () {
        return (this.comments.length == 0)
      }
    },
    mounted () {
      this.getActivityStatus();
      this.getList()
    },
    methods: {
      getActivityStatus () {
        this.get('/system', {}, { errmsg: '获取活动状态失败' }).then(res => {
          if (res.success) {
            this.activityStatus = res.data.data.is_activity_open;
          }
        })
      },
      getList (currentPage = 1) {
        let pd = {};
        pd.p = currentPage;
        pd.s = this.pageSize;
        pd.state = this.searchForm.state;
        pd.name = this.searchForm.name;
        pd.car_num = this.searchForm.car_num;
        pd.city = this.searchForm.city;
        pd.down_role = this.searchForm.down_role;
        pd.is_activity = true;

        this.get('/api/v1/traces', pd, { loading: 'xhrPending', errmsg: '获取情报列表失败' })
          .then(res => {
            if (res.success && res.data.rows) {
              this.comments = res.data.rows.map((e, i) => {
                let ele = e;
                let photo = e.car_photo
                ele.isAli = e.car_photo.includes('aixuedaiimg')
                ele.time = e.create_at.split(' ')[0];
                ele.location = e.location || '无';
                ele.fingerprint = e.fingerprint || '未成功获取';
                if (e.car_photo && e.car_photo.includes('aixuedaiimg')) {
                  ele.car_photo = e.car_photo
                  ele.car_photo_slim = photo
                } else {
                  ele.car_photo = cdn + e.car_photo + '?imageView2/0/w/100'
                  ele.car_photo_slim = cdn + photo + '?imageslim'
                }
                if (ele.fingerprint != '未成功获取') {
                  let lnglatXY = ele.fingerprint.split(',').map(e => Number(e).toFixed(6));
                  this.regeocoder(lnglatXY)
                    .then(address => {
                      this.comments[i].fingerprint = address;
                    });
                }

                if (ele.isAli) {
                  axios.post('/getAliGpsInfo', {
                    url: photo + '?x-oss-process=image/info'
                  }).catch(e => {
                    console.log(e)
                  }).then(data => {
                    let res = data.data
                    this.comments[i].photo_time = res.time
                    if (res.success) {
                      return this.regeocoder(res.lnglatXY)
                    } else {
                      this.comments[i].photo_city = res.lnglatXY;
                    }

                  }).then(address => {
                    this.comments[i].photo_city = address;
                  })
                } else {
                  axios.get(cdn + photo + '?exif').catch(err => {
                    console.warn(err)
                  }).then(data => {
                    let res = data.data;
                    let Longitude;
                    let Latitude;
                    if (res.DateTimeOriginal) {
                      this.comments[i].photo_time = res.DateTimeOriginal.val;
                    }

                    if (res.GPSLongitude) {
                      Longitude = this.transformTude(res.GPSLongitude.val);
                      Latitude = this.transformTude(res.GPSLatitude.val);
                      return [Longitude, Latitude]
                    } else {
                      this.comments[i].photo_city = '未成功获取';
                      return Promise.reject('')
                    }

                  }).then(lnglatXY => {
                    return this.regeocoder(lnglatXY)
                  }).then(address => {
                    this.comments[i].photo_city = address;
                  });
                }

                return ele
              });
              this.pageIndex = res.data.page + 1;
              this.total = res.data.total;
            } else {
              this.comments = [];
            }
          })
      },
      handleTabSelect (state) {
        this.searchForm.state = state;
        this.getList();
      },
      changeIndex (pi) {
        this.getList(pi)
      },
      viewImg (imgSrc, msg) {
        this.pointImgSlim = imgSrc;
        this.pointMsg = msg;
        this.imgVisible = true;
      },
      closeView () {
        this.imgVisible = false;
        this.pointImgSlim = ''
      },
      search () {
        this.getList()
      },
      pass (id) {
        this.$confirm('确认情报有效，请慎重？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = new FormData();
          postData.append('verify', 1);

          this.jax(`/api/v1/traces/${id}/verify`, postData, { errmsg: '请求失败，请稍后再试' })
            .then(res => {
              if (res.success) {
                this.msg('成功通过', 'success');
                this.getList();
                b.$emit('resCount');
              }
            })
        }).catch(() => {
        })
      },
      refuse (id) {
        this.$confirm('确认删除情报吗，请慎重？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = new FormData();
          postData.append('verify', 0);

          this.jax(`/api/v1/traces/${id}/verify`, postData, { errmsg: '请求失败，请稍后再试' })
            .then(res => {
              if (res.success) {
                this.msg('成功拒绝', 'success');
                this.getList();
                b.$emit('resCount');
              }
            })
        }).catch(() => {
        })
      },
      regeocoder (lnglatXY) {
        let self = this;
        return new Promise((resolve, reject) => {
          this.geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              resolve(self.geocoder_CallBack(result))
            } else {
              console.log('获取地理位置失败');
            }
          });
        })
      },
      geocoder_CallBack(data) {
        return data.regeocode.formattedAddress; //返回地址描述
      },
      transformTude (tude) {
        let rst = tude.split(', ').map(e => Number(e));
        return (rst[0] + rst[1] / 60 + rst[2] / 3600).toFixed(6)
      },
      transformAli (tude) {
        let arr = /(\d+)deg\s(\d+)\'\s(\d+.\d+)\"/.exec(tude)
        return arr[1] + ', ' + arr[2] + ', ' + arr[3]
      },
      activityStatusChange (val) {
        this.$prompt('请输入密码', '改变活动状态', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /123456/,
          inputErrorMessage: '密码不正确'
        }).then(({ value }) => {
          let postData = new FormData();
          postData.append('on', val ? 1 : 0);

          this.jax(`/system/activity`, postData, {
            errmsg: `活动${val ? '开启' : '关闭'}失败，请稍后再试`,
            errcb: this.rollbackStatus
          })
            .then(res => {
              if (res.success) {
                this.msg(`成功${val ? '开启' : '关闭'}活动`, 'success');
              } else {
                this.activityStatus = !val
              }
            })
        }).catch(() => {
          this.activityStatus = !val
        });
      },
      rollbackStatus (val) {
        this.activityStatus = !val
      }
    },
  };
</script>

<template>
  <div class="comments">
    <el-menu default-active="3" mode="horizontal" @select="handleTabSelect" layout="row center-left">
      <el-menu-item index="3">待审查</el-menu-item>
      <el-menu-item index="0,1">已通过</el-menu-item>

      <div class="cb__bar-left" layout="row center-left">
        <span class="cb__bar-txt">活动开关</span>
        <el-switch
            v-model="activityStatus"
            on-text=""
            off-text=""
            @change="activityStatusChange"
        >
        </el-switch>
      </div>
      <div self="right" class="cb__bar-right cb__bar-right--800" layout="row center-justify">
        <el-input
            class="tasks__tool-input"
            placeholder="按线人名字搜索"
            icon="search"
            @change="search"
            v-model="searchForm.name">
        </el-input>
        <el-input
            class="tasks__tool-input"
            placeholder="按市搜索"
            icon="search"
            @change="search"
            v-model="searchForm.city">
        </el-input>
        <el-select v-model="searchForm.down_role" @change="search" placeholder="按线人类型">
          <el-option label="全部" value=""></el-option>
          <el-option label="A类" value="0"></el-option>
          <el-option label="B类" value="1"></el-option>
          <el-option label="C类" value="2"></el-option>
        </el-select>
        <el-input
            class="tasks__tool-input"
            placeholder="按车牌搜索"
            icon="search"
            @change="search"
            v-model="searchForm.car_num">
        </el-input>
      </div>
    </el-menu>
    <!-- list-->
    <div class="comments__content" v-loading.body="xhrPending">
      <div class="wh-table">
        <div class="wh-table__thead" layout="row center-left">
          <div class="th w10">填写车牌号</div>
          <div class="th w14">查看照片</div>
          <div class="th w12">线人信息</div>
          <div class="th w10">上传时间</div>
          <div class="th w15">GPS定位</div>
          <div class="th w15">照片拍摄地/时间</div>
          <div class="th w12 tac">描述地址</div>
          <div class="th w10 tac"><i class="el-icon-more"></i></div>
        </div>
        <div v-if="isListEmpty" class="wh-table__tbody--empty">无记录</div>
        <div v-else class="wh-table__tbody" layout="row center-left" v-for="(comment, index) in comments">
          <div class="td w10">
            <h5 class="wh-table__em">{{comment.car_number}}</h5>
          </div>
          <div class="td w14 comments__view" @click="viewImg(comment.car_photo_slim, comment.car_number)">
            <div class="wh-table__thumbnail wh-table__thumbnail--vertical" data-content="点击查看情报照片">
              <img :src="comment.car_photo"
                   class="wh-table__thumbnail-inner">
            </div>
          </div>
          <div class="td w12">
            <p class="wh-table__em">{{comment.name}}</p>
            <p>{{comment.city}}</p>
            <p>{{comment.phone}}</p>
          </div>
          <div class="td w10">
            <el-tooltip placement="top" :content="comment.create_at">
              {{comment.time}}


            </el-tooltip>
          </div>
          <div class="td w15">{{comment.fingerprint}}</div>
          <div class="td w15">
            <p>{{comment.photo_city}}</p>
            <hr>
            <p>{{comment.photo_time}}</p>
            <hr>
            <p>上传时间：{{comment.last_update_at}}</p>
          </div>
          <div class="td w15 tac">{{comment.location}}</div>
          <div class="td w10" layout="row center-right">
            <el-button type="primary" v-if="comment.state == 3" @click="pass(comment.id)">通过</el-button>
            <el-button type="danger" v-if="comment.state == 3 || comment.state == 1" plain
                       @click="refuse(comment.id)">拒绝


            </el-button>
          </div>
        </div>
        <!-- pagination-->
        <div v-if="!isListEmpty" class="wh-table__page" layout="row center-center">
          <el-pagination
              @current-change="changeIndex"
              :current-page="pageIndex"
              :page-size="pageSize"
              :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- viewImg-->
    <div v-if="imgVisible" class="img__modal" layout="column center-center">
      <i class="img__close el-icon-close" @click="closeView"></i>
      <p class="point__msg">任务车牌号：{{pointMsg}}</p>
      <img :src="pointImgSlim" class="img__big"/>
    </div>
  </div>
</template>